<?php
/**
 * 拼团管理
 *
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */

use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');
class promotion_pintuanControl extends SystemControl{
    const PINTUAN_STATE_UNREVIEWED   = 0;    //默认：未审核
    const PINTUAN_STATE_PASS         = 1;    //通过
    const PINTUAN_STATE_FAIL         = 2;    //未通过
    const PINTUAN_STATE_REAPPLY      = 3;    //再次申请
    const PINTUAN_STATE_CLOSE        = 4;    //活动关闭
    const PINTUAN_STATE_DELETE_ADMIN = 5;    //管理员删除
    const PINTUAN_STATE_SOFT_DELETE  = 6;    //软删除

    private $mansong_state_array = array(
        self::PINTUAN_STATE_UNREVIEWED   => '未审核',
        self::PINTUAN_STATE_PASS         => '通过',
        self::PINTUAN_STATE_FAIL         => '未通过',
        self::PINTUAN_STATE_REAPPLY      => '再次申请',
        self::PINTUAN_STATE_CLOSE        => '活动关闭',
        self::PINTUAN_STATE_DELETE_ADMIN => '管理员删除',
        self::PINTUAN_STATE_SOFT_DELETE  => '删除'
    );
    public function __construct(){
        parent::__construct();
        Language::read('marketing_activity');
        $model_pintuan = Model('p_pintuan');
        $model_pintuan->getStateArray();
    }
    /**
     * 得到操作类型
     * @return array
     */
    public function getMansongStateArray()
    {
        return $this->mansong_state_array;
    }
    /**
     * 默认
     */
    public function indexOp() {
        $this->pintuan_listOp();

    }

    /**
     * 活动列表
     */
    public function pintuan_listOp()
    {
        $this->show_menu('pintuan_list');
        Tpl::showpage('promotion_pintuan.list');
    }

    /**
     * 活动列表
     */
    public function pintuan_list_xmlOp()
    {
        $condition = array();
        if ($_REQUEST['advanced']) {
            if (strlen($q = trim((string) $_REQUEST['pintuan_name']))) {
                $condition['pintuan_name'] = array('like', '%' . $q . '%');
            }
            if (strlen($q = trim((string) $_REQUEST['store_name']))) {
                $condition['store_name'] = array('like', '%' . $q . '%');
            }
            if ($_REQUEST['state'] != '') {
                $condition['state'] = intval($_REQUEST['state']);
            }

            $pdates = array();
            if (strlen($q = trim((string) $_REQUEST['pdate1'])) && ($q = strtotime($q . ' 00:00:00'))) {
                $pdates[] = "end_time >= {$q}";
            }
            if (strlen($q = trim((string) $_REQUEST['pdate2'])) && ($q = strtotime($q . ' 00:00:00'))) {
                $pdates[] = "start_time <= {$q}";
            }
            if ($pdates) {
                $condition['pdates'] = array(
                    'exp',
                    implode(' or ', $pdates),
                );
            }

        } else {
            if (strlen($q = trim($_REQUEST['query']))) {
                switch ($_REQUEST['qtype']) {
                    case 'pintuan_name':
                        $condition['pintuan_name'] = array('like', '%'.$q.'%');
                        break;
                    case 'store_name':
                        $condition['store_name'] = array('like', '%'.$q.'%');
                        break;
                }
            }
        }

        $model_pintuan = Model('p_pintuan');
        $pintuan_list = (array) $model_pintuan->getList($condition, $_REQUEST['rp']);
        $state_array = $model_pintuan->getStateArray();

        $flippedOwnShopIds = array_flip(Model('store')->getOwnShopIds());

        $data = array();
        $data['now_page'] = $model_pintuan->shownowpage();
        $data['total_num'] = $model_pintuan->gettotalnum();

        foreach ($pintuan_list as $val) {

            $o  = '<a class="btn orange" href="' . urlAdminShop('promotion_pintuan', 'pintuan_detail', array(
                'pintuan_id' => $val['pintuan_id'],
            )) . '"><i class="fa fa-check-circle"></i>审核</a>';

            $o  .= '<a class="btn red confirm-on-click" href="javascript:;" data-href="' . urlAdminShop('promotion_pintuan', 'pintuan_del', array(
                'pintuan_id' => $val['pintuan_id'],
            )) . '"><i class="fa fa-trash-o"></i>删除</a>';

            $o .= '<span class="btn"><em><i class="fa fa-cog"></i>设置<i class="arrow"></i></em><ul>';

            if ($val['state']) {
                $o .= '<li><a class="confirm-on-click" href="javascript:;" data-href="' . urlAdminShop('promotion_pintuan', 'pintuan_cancel', array(
                    'pintuan_id' => $val['pintuan_id'],
                )) . '">取消活动</a></li>';
            }

            $o .= '<li><a class="confirm-on-click" href="' . urlAdminShop('promotion_pintuan', 'pintuan_detail', array(
                'pintuan_id' => $val['pintuan_id'],
            )) . '">活动详细</a></li>';

            $o .= '</ul></span>';

            $i = array();
            $i['operation'] = $o;
            $i['pintuan_name'] = $val['pintuan_name'];
            $i['store_name'] = '<a target="_blank" href="' . urlShop('show_store', 'index', array(
                'store_id'=>$val['store_id'],
            )) . '">' . $val['store_name'] . '</a>';

            if (isset($flippedOwnShopIds[$val['store_id']])) {
                $i['store_name'] .= '<span class="ownshop">[自营]</span>';
            }

            $i['start_time_text'] = date('Y-m-d H:i', $val['start_time']);
            $i['end_time_text'] = date('Y-m-d H:i', $val['end_time']);

            $i['min_num'] = $val['min_num'];
            $i['state_text'] = $val['end_time'] > TIMESTAMP ? $state_array[$val['state']]:'已结束';

            $data['list'][$val['pintuan_id']] = $i;
        }

        echo Tpl::flexigridXML($data);
        exit;
    }

    /**
     * 活动取消
     **/
    public function pintuan_cancelOp() {
        $pintuan_id = intval($_REQUEST['pintuan_id']);
        $model_pintuan = Model('p_pintuan');
        $result = $model_pintuan->cancel(array('pintuan_id' => $pintuan_id));
        if($result) {
            $this->log('取消拼团活动，活动编号'.$pintuan_id);
            $this->jsonOutput();
        } else {
            $this->jsonOutput('操作失败');
        }
    }

    /**
     * 活动删除
     **/
    public function pintuan_delOp() {
        $pintuan_id = intval($_REQUEST['pintuan_id']);
        $model_pintuan = Model('p_pintuan');
        $result = $model_pintuan->del(array('pintuan_id' => $pintuan_id));
        if($result) {
            $this->log('删除拼团活动，活动编号'.$pintuan_id);

            $this->jsonOutput();
        } else {
            $this->jsonOutput('操作失败');
        }
    }

    /**
     * 活动详细信息
     **/
    public function pintuan_detailOp() {
        $states = $this->getMansongStateArray();
        Tpl::output('states', $states);

        $pintuan_id = intval($_GET['pintuan_id']);
        $marketing_activity_id = intval($_GET['marketing_activity_id']);

        $model_pintuan = Model('p_pintuan');
        $condition = array();

        if(!isset($_GET['p_pintuan'])){
            $p_pintuan = $model_pintuan->getInfo(array('marketing_activity_id'=>$marketing_activity_id));
            $condition['p_pintuan.pintuan_id'] = $p_pintuan['pintuan_id'];
        }
        $pintuan_info = $model_pintuan->getInfo($condition);
        Tpl::output('pintuan_info',$pintuan_info);

        //获取商品列表
        $pintuan_goods_list = $model_pintuan->getGoodsListState($condition);
        Tpl::output('list',$pintuan_goods_list);
        Tpl::output('check_state_array',  $this->getMansongStateArray());
        Tpl::output('goods_state_array',  Model('goods')->getGoodsStateArray());
        Tpl::showpage('promotion_pintuan.detail');
    }

    /**
     * 活动细节列表XML
     */
    public function detail_xmlOp()
    {
        $pintuan_id = isset($_GET['pintuan_id']) ? (int)$_GET['pintuan_id'] : 0;

        $condition                          = array();
        $condition['p_pintuan.pintuan_id'] = $pintuan_id;

        if ($_REQUEST['advanced']) { //高级搜索
            if (strlen($q = trim((string)$_REQUEST['store_name']))) {  //店铺名称
                $condition['p_pintuan_goods.store_name'] = $q;
            }
            if (strlen($q = trim((string)$_REQUEST['goods_name']))) {   //商品名称
                $condition['p_pintuan_goods.goods_name'] = $q;
            }
            if (strlen($q = trim((string)$_REQUEST['marketing_activity_detail_state']))) {
                $condition['p_pintuan_goods.pintuan_state'] = (int)$q;
            }
        } else {
            if (strlen($q = trim($_REQUEST['query'])) > 0) {
                switch ($_REQUEST['qtype']) {
                    case 'store_name':
                        $condition['p_pintuan_goods.store_name'] = $q;
                        break;
                    case 'goods_name':
                        $condition['p_pintuan_goods.goods_name'] = $q;
                        break;
                }
            }
        }

        $model_pintuan = Model('p_pintuan');
        $list = $model_pintuan->getGoodsListState($condition, 0, $_REQUEST['rp']);

        $data              = array();
        $data['now_page']  = $model_pintuan->shownowpage();
        $data['total_num'] = $model_pintuan->gettotalnum();

        $goods_state_array = Model('goods')->getGoodsStateArray();
        $check_state_array = $this->getMansongStateArray();

        foreach ($list as $val) {
            $o  = '<a class="btn green" target="_blank" href="' . urlShop('goods', 'index', array('goods_id' => $val['goods_id'])) .'"><i class="fa fa-list-alt"></i>查看</a>';
            $o .= '<span class="btn"><em><i class="fa fa-cog"></i>设置<i class="arrow"></i></em><ul>';
            if ($val['pintuan_state'] != self::PINTUAN_STATE_PASS) {
                $o .= '<li><a class="confirm-on-click"  href="javascript:;" data-href="index.php?act=promotion_pintuan&op=deal&pintuan_id=' . $val['pintuan_id'] . '&check_state=' . self::PINTUAN_STATE_PASS . '&pintuan_goods_id=' .
                    $val['pintuan_goods_id'] .
                    '">通过</a></li>';
            }
            if ($val['pintuan_state'] != self::PINTUAN_STATE_FAIL) {
                $o .= '<li><a class="confirm-on-click" href="javascript:;" data-href="index.php?act=promotion_pintuan&op=deal&pintuan_id=' . $val['pintuan_id'] . '&check_state=' . self::PINTUAN_STATE_FAIL . '&pintuan_goods_id=' .
                    $val['pintuan_goods_id'] .
                    '">拒绝</a></li>';
            }
            if ($val['pintuan_state'] != self::PINTUAN_STATE_PASS) {
                $o .= '<li><a class="confirm-on-click" href="javascript:;" data-href="index.php?act=promotion_pintuan&op=del&pintuan_id=' . $val['pintuan_id'] . '&check_state=' . self::PINTUAN_STATE_DELETE_ADMIN . '&pintuan_goods_id=' .
                    $val['pintuan_goods_id'] .
                    '">删除</a></li>';
            }
            $o .= '</ul></span>';
            //列表操作按钮 - end
            $i['operation']                                     = $o;
            $i['xianshi_goods_sort']                           = '<span class="editable" title="可编辑" style="width:50px;" data-live-inline-edit="xianshi_goods_sort">' . $val['xianshi_goods_sort'] . '</span>';
            $i['goods_name']                                    = $val['goods_name'];
            $i['goods_state_text']                              = $goods_state_array[$val['goods_state']];
            $i['store_name']                                    = '<a target="_blank" href="' . urlShop('show_store', 'index', array('store_id' => $val['store_id'])) . '">' . $val['store_name'] . '</a>';
            $i['sc_name']                                       = (isset($val['sc_name']) && !empty($val['sc_name'])) ? $val['sc_name'] : '';
            $i['price_contrast']                                = $val['goods_price'] .'/'. $val['pintuan_price'];
            $check_time = $val['check_time'] != 0 ? date('Y-m-d H:i:s' ,$val['check_time']) : '';
            $i['apply_check']                                   = date('Y-m-d H:i:s', $val['create_time']) .'<br/>' . $check_time;

            $activity_type                              = isset($check_state_array[$val['pintuan_state']]) ? $check_state_array[$val['pintuan_state']] : '';    //审核状态text
            $i['check_state_text']  =  ( $val['pintuan_state'] == self::PINTUAN_STATE_PASS ) ? (($val['start_time'] > TIMESTAMP) ? '待上线' : (($val['end_time'] > TIMESTAMP) ? '进行中' : '已过期')) : $activity_type;    //活动状态text

            $i['check_admin_name']                              = $val['check_admin_name'];
            $data['list'][$val['pintuan_goods_id']] = $i;
        }

        echo Tpl::flexigridXML($data);
        exit;
    }
    /**
     * 活动内容处理
     */
    public function dealOp()
    {

        $ids = array();
        foreach (explode(',', (string)$_REQUEST['pintuan_goods_id']) as $i) {
            $ids[(int)$i] = null;
        }
        unset($ids[0]);
        $ids = array_keys($ids);

        if (empty($ids)) {
            showMessage(Language::get('activity_detail_del_choose_detail'));
        }
        //修改数据
        $p_pintuan_goods    = Model('p_pintuan_goods');
        $pintuan_goods_id = isset($_REQUEST['pintuan_goods_id']) ? (int)$_REQUEST['pintuan_goods_id'] : 0;
        $update_array['pintuan_state'] = isset($_REQUEST['check_state']) ? (int)$_REQUEST['check_state'] : 0;
        //增加添加人信息
        $update_array['check_time']       = TIMESTAMP;
        $update_array['check_admin_id']   = $this->admin_info['id'];
        $update_array['check_admin_name'] = $this->admin_info['name'];
        if (isset($_REQUEST['remark'])) $update_array['remark'] = $_REQUEST['remark'];

        for ($i=0;count($ids) > $i ;$i++){
            $result = $p_pintuan_goods->where("pintuan_goods_id=".$ids[$i])->update($update_array);
        }

        if($result) {
            if($_REQUEST['check_state'] == 1){
                $this->log('审核通过拼团活动，活动编号'.$pintuan_goods_id);
                $this->jsonOutput();
            }else{
                $this->log('审核拒绝拼团活动，活动编号'.$pintuan_goods_id);
                $this->jsonOutput();
            }
        } else {
            // return array('code'=>200 ,'msg'=>'操作失败');
            $this->jsonOutput('操作失败');
        }

    }
    /*删除拼团产品*/
    public function delOp(){
        $ids = array();
        foreach (explode(',', (string)$_REQUEST['pintuan_goods_id']) as $i) {
            $ids[(int)$i] = null;
        }
        unset($ids[0]);
        $ids = array_keys($ids);
        $model_p_pintuan_goods = Model('p_pintuan_goods');
        $param['pintuan_goods_id'] = array('in',$ids);
        $result = $model_p_pintuan_goods->del($param);
        if($result){
            $this->log('删除拼团活动产品，活动编号'.$_GET['pintuan_id'].',产品编号'.$_GET['pintuan_goods_id']);
            $this->jsonOutput();
        }else{
            $this->jsonOutput('操作失败');
        }
    }
    /**
     * 套餐管理
     */
    public function pintuan_quotaOp()
    {
        $this->show_menu('pintuan_quota');
        Tpl::showpage('promotion_pintuan_quota.list');
    }

    /**
     * 套餐管理XML
     */
    public function pintuan_quota_xmlOp()
    {
        $condition = array();

        if (strlen($q = trim($_REQUEST['query']))) {
            switch ($_REQUEST['qtype']) {
                case 'store_name':
                    $condition['store_name'] = array('like', '%'.$q.'%');
                    break;
            }
        }

        $model_pintuan = Model('p_pintuan');
        $list = (array) $model_pintuan->getQuotaList($condition, $_REQUEST['rp']);

        $data = array();
        $data['now_page'] = $model_pintuan->shownowpage();
        $data['total_num'] = $model_pintuan->gettotalnum();

        foreach ($list as $val) {
            $i = array();
            $i['operation'] = '<span>--</span>';

            $i['store_name'] = '<a target="_blank" href="' . urlShop('show_store', 'index', array(
                'store_id' => $val['store_id'],
            )) . '">' . $val['store_name'] . '</a>';

            $i['start_time_text'] = date("Y-m-d", $val['start_time']);
            $i['end_time_text'] = date("Y-m-d", $val['end_time']);

            $data['list'][$val['quota_id']] = $i;
        }

        echo Tpl::flexigridXML($data);
        exit;
    }

    /**
     * 设置
     **/
    public function pintuan_settingOp() {
        $model_setting = Model('setting');
        $setting = $model_setting->GetListSetting();
        Tpl::output('setting',$setting);

        $this->show_menu('pintuan_setting');
        Tpl::showpage('promotion_pintuan.setting');
    }

    public function pintuan_setting_saveOp() {
        $promotion_pintuan_price = intval($_POST['promotion_pintuan_price']);
        if($promotion_pintuan_price < 0) {
            $promotion_pintuan_price = 20;
        }
        $model_setting = Model('setting');
        $update_array = array();
        $update_array['promotion_pintuan_price'] = $promotion_pintuan_price;
        $result = $model_setting->updateSetting($update_array);
        if ($result){
            $this->log('修改拼团价格为'.$promotion_pintuan_price.'元');
            showMessage(Language::get('nc_common_save_succ'),'');
        }else {
            showMessage(Language::get('nc_common_save_fail'),'');
        }
    }

    /**
     * 页面内导航菜单
     *
     * @param string    $menu_key   当前导航的menu_key
     * @param array     $array      附加菜单
     * @return
     */
    private function show_menu($menu_key) {
        $menu_array = array(
            'pintuan_list'=>array('menu_type'=>'link','menu_name'=>'活动列表','menu_url'=>'index.php?act=promotion_pintuan&op=pintuan_list'),
            'pintuan_quota'=>array('menu_type'=>'link','menu_name'=>'套餐管理','menu_url'=>'index.php?act=promotion_pintuan&op=pintuan_quota'),
            'pintuan_setting'=>array('menu_type'=>'link','menu_name'=>'设置','menu_url'=>'index.php?act=promotion_pintuan&op=pintuan_setting'),
        );
        $menu_array[$menu_key]['menu_type'] = 'text';
        Tpl::output('menu',$menu_array);
    }

    /**
     * 审核状态修改
     * @author  benald 
     * @return  json
     **/
    public function pintuan_stateOp() {
        $pintuan_goods_id = intval($_REQUEST['pintuan_goods_id']);
        $pintuan_state  = intval($_REQUEST['pintuan_state']);
        $remark         = trim($_REQUEST['remark']);
        $model_pintuan = Model('p_pintuan_goods');
        $pintuan_state_now = $model_pintuan->where("pintuan_goods_id=".$pintuan_goods_id)->field('pintuan_state')->find();
        if($pintuan_state_now['pintuan_state'] == $pintuan_state){
             $this->jsonOutput('请勿重复操作');
        }

        $update_array['check_time']       = TIMESTAMP;
        $update_array['check_admin_id']   = $this->admin_info['id'];
        $update_array['check_admin_name'] = $this->admin_info['name'];
        $update_array['pintuan_state']     = $pintuan_state;

        if($pintuan_state == 2){
            $update_array['remark']           = $remark;
            $result = $model_pintuan->where("pintuan_goods_id=".$pintuan_goods_id)->update($update_array);
        }else{
            $result = $model_pintuan->where("pintuan_goods_id=".$pintuan_goods_id)->update($update_array);
        }
        if($result) {
            if($pintuan_state == 1){
                $this->log('审核通过拼团活动，活动编号'.$pintuan_goods_id);
                $this->jsonOutput('通过成功');
            }else{
                 $this->log('审核拒绝拼团活动，活动编号'.$pintuan_goods_id);
                $this->jsonOutput('已拒绝');
            }
        } else {
            $this->jsonOutput('操作失败');
        }
    }

    /**
     * 排序修改
     * @author  benald
     * @return  json
     **/
    public function pintuan_sortOp() {
        $pintuan_goods_id = intval($_REQUEST['id']);
        $sort = intval($_REQUEST['value']);

        $model_pintuan = Model('p_pintuan_goods');

        $update_array['xianshi_goods_sort']     = $sort;

        $result = $model_pintuan->where("pintuan_goods_id=".$pintuan_goods_id)->update($update_array);

        if($result) {
            $this->log('修改砍价商品排序，活动编号'.$pintuan_goods_id);
            $this->jsonOutput('修改成功');
        } else {
            $this->jsonOutput('操作失败');
        }
    }

}
